#!/bin/bash
set -e

# This can be uncommented once it no longer throws an error exit code.
# ./scripts/regenerate_docs

# By default GCB uses master branch name. This code change it to main.
if [ "master" == "$(git branch --show-current)" ]; then
    git branch -m main
fi

if [ "$(git status --porcelain)" ]; then
    echo "There are uncommitted changes; aborting." 1>&2
    exit 1
fi

# Run all the tests.
bazel run @nodejs//:yarn config set registry https://us-npm.pkg.dev/artifact-foundry-prod/ah-3p-staging-npm/
bazel run @nodejs//:npm install
bazel test //... --build_tests_only

# After the code is build with Airlock dependencies, we change the registry to public npmjs
# to publish our npm package.
bazel run @nodejs//:npm config set registry https://registry.npmjs.org/

VERSION=$(cat version.bzl | grep DF_VERSION | awk '{ print $3 }' | sed "s/\"//g")

TAG=next

# If the version is a normal release (1.2.3) and not pre-release e.g (1.2.3-alpha.1) then publish with the 'latest' tag.
if [[ "$VERSION" =~ [0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    TAG=latest

    if [ "main" != "$(git branch --show-current)" ]; then
        echo "Not on the 'main' branch; aborting." 1>&2
        exit 1
    fi
fi

echo "Publishing as '$TAG' based on version: $VERSION"

bazel run packages/@dataform/cli:package.publish -- --tag=$TAG
bazel run packages/@dataform/core:package.publish -- --tag=$TAG
